/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.example;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction;


//下面是数据


//下面是具体的运行的代码


class FlinkCountWindowDemo {

	public static void main(String[] args) throws Exception {
		final ParameterTool params = ParameterTool.fromArgs(args);
		final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
		env.getConfig().setGlobalJobParameters(params);
		env.setParallelism(1);
		final int windowSize = params.getInt("window", 3);//統計幾條數據
		final int slideSize = params.getInt("slide", 2);
//		每輸入兩條數據就統計最近的3條數據

		// read source data
		DataStreamSource<Tuple2<String, String>> inStream = env.addSource(new StreamingDataSource());

		// calculate
		DataStream<Tuple2<String, String>> outStream;
		outStream = inStream
				.keyBy(0)//統計第0個元素的數量
				.countWindow(windowSize,slideSize)//統計幾條數據,也稱爲窗口寬度
				.reduce(new ReduceFunction<Tuple2<String, String>>() {
							@Override
							public Tuple2<String, String> reduce(Tuple2<String, String> value1, Tuple2<String, String> value2) throws Exception {
								System.out.printf("value1.f0=%s\n",value1.f0);
								System.out.printf("value1.f1=%s\n",value1.f1);
								System.out.printf("value2.f0=%s\n",value2.f0);
								System.out.printf("value2.f1=%s\n",value2.f1);
								System.out.printf("-------------------------------------\n");

								return Tuple2.of(value1.f0, value1.f1 +  value2.f1);
								//返回新的元組(a,以及兩個元組的的各自第二個元素作爲拼接後的數據)
								//返回作爲新的元組
								//因爲聚合操作是a,所以這裏是value.f0, value2,f0和value的f0是一樣的,所以沒有出現
							}
						}

				);
		outStream.print();
		env.execute("WindowWordCount");
	}
}
